﻿using PixivVideo.Currency.IoUtils;
using PixivVideo.Utils.Helper;
using PixivVideo.Utils.IoUtils;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

namespace PixivVideo.Currency
{
    internal class WebHelper
    {
      
        /// <summary>
        /// 同步获取html代码
        /// </summary>
        /// <param name="Url"></param>
        /// <returns></returns>
        public static string PcGet(String Url)
        {
            return (HttpGet(Url, new WebHelper().PcWebHeader(Url)));
        }

        /// <summary>
        /// 同步获取html代码
        /// </summary>
        /// <param name="Url"></param>
        /// <returns></returns>
        public static string HttpGet(String Url, WebHeaderCollection webHeaderCollection)
        {
            String HtmlCode = "";

            using (WebClient webClient = new WebClient())
            {
                try
                {
                    webClient.Headers = webHeaderCollection;
                    HtmlCode = new StreamReader(webClient.OpenRead(Url)).ReadToEnd();
                }
                catch (Exception ex)
                {
                    PrintLog.Log(ex);
                }
            }
            return HtmlCode;
        }

        /// <summary>
        /// 同步获取html代码
        /// </summary>
        /// <param name="Url"></param>
        /// <returns></returns>
        public static string MobileGet(String Url)
        {
            return (HttpGet(Url, new WebHelper().MobileWebHeader(Url)));
        }

        /// <summary>
        /// 发送Post请求并返回结果，使用UTF8
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="PostData"></param>
        /// <returns></returns>
        public string HttpPost(string Url, string PostData)
        {
            WebHeaderCollection webHeaderCollection = new WebHelper().PcWebHeader(Url);

            webHeaderCollection.Add("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            return HttpPost(Url, PostData, webHeaderCollection);
        }

        /// <summary>
        /// 发送Post请求并返回结果，使用UTF8  可自定义请求头
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="PostData"></param>
        /// <returns></returns>
        public string HttpPost(String Url, string PostData, WebHeaderCollection webHeaderCollection)
        {
            using (WebClient PostWebClient = new WebClient())
            {
                PostWebClient.Headers = webHeaderCollection;
                try
                {
                    byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(PostData);

                    byte[] responseArray = PostWebClient.UploadData(Url, byteArray);

                    return Encoding.UTF8.GetString(responseArray);
                }
                catch (Exception ex)
                {
                    PrintLog.Log(ex);
                }
            }
            return "";
        }

        /// <summary>
        /// 获取网址包含的主域名
        /// </summary>
        /// <param name="Url"></param>
        /// <returns></returns>
        public string GetHost(String Url)
        {
            try
            {
                return new Uri(Url).Host;
            }
            catch (Exception ex)
            {
                PrintLog.Log(ex);
            }
            return "";
        }

        /// <summary>
        /// 获取301OR302OR404转移状态码，侦测资源是否发生了转移 转移返回true
        /// </summary>
        /// <param name="Link"></param>
        /// <returns></returns>
        public bool GetMoveStatus(String Link)
        {
            try
            {
                HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(Link);
                httpReq.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36";
                httpReq.AllowAutoRedirect = false;//禁止自动重定向
                using (HttpWebResponse httpRes = (HttpWebResponse)httpReq.GetResponse())
                {
                    if (httpRes.StatusCode == HttpStatusCode.Moved || httpRes.StatusCode == HttpStatusCode.Found)
                    {
                        // Code for moved resources goes here.
                        return true;
                    }
                }
            }
            catch (Exception ex)
            {
                string link = ex.Message;
                if (link.IndexOf("404") > 0)
                    return true;
                Console.WriteLine(ex.Message);
            }
            return false;
        }

        /// <summary>
        /// 创建一个文件名路径
        /// </summary>
        /// <param name="FileUrl"></param>
        /// <param name="FloderPath"></param>
        /// <param name="AutoShort"></param>
        /// <returns></returns>
        public string CreateFilePath(string FileUrl, string FloderPath, bool AutoShort = true)
        {
            if (!new FloderHelper().FloderExits(FloderPath, true))
                return "";

            try
            {
                string FileName = new FileNameHelper().GetFileName(FileUrl);
                if (FileName != "")
                    FileUrl = FloderPath + FileName;
                else
                    FileUrl = new FileNameHelper().CreateRandomFileName(FloderPath, new FileNameHelper().GetFileType(FileUrl));
                if (AutoShort && FileUrl.Length > 200)//文件名过长的情况进行溢出截断
                                                      //  FileUrl = FloderPath + DateTime.Now.ToFileTime().ToString() + Path.GetFileName(FileUrl);
                    FileUrl = new FileNameHelper().CreateRandomFileName(FloderPath, new FileNameHelper().GetFileType(FileUrl));
            }
            catch (Exception ex)
            {
                PrintLog.Log(ex);
            }

            return FileUrl;
        }
        /// <summary>
        /// 下载文件列表
        /// </summary>
        /// <param name="FileList"></param>
        /// <param name="FloderPath"></param>
        /// <param name="headers"></param>

        public void FileListDownload(List<string> FileList, string FloderPath, WebHeaderCollection headers)
        {
            int CompltedCount = 0;
            foreach (string FileUrl in FileList)
            {

                new PrintLog().PercentLog(FileList.Count, ++CompltedCount);
                Console.WriteLine("下载完成" + new FileNameHelper().GetFileName(FileDownload(FileUrl, FloderPath, headers)));
            }
        }
        /// <summary>
        /// 文件下载辅助
        /// </summary>
        /// <param name="FileUrl"></param>
        /// <param name="FloderPath"></param>
        /// <returns></returns>
        public string FileDownload(string FileUrl, string FloderPath)
        {

            return FileDownload(FileUrl, FloderPath, PcWebHeader());
        }
        /// <summary>
        /// 文件下载辅助
        /// </summary>
        /// <param name="FileUrl"></param>
        /// <param name="FloderPath"></param>
        /// <param name="headers"></param>
        /// <returns></returns>

        public string FileDownload(string FileUrl, string FloderPath, WebHeaderCollection headers)
        {

            string FileName = new FileNameHelper().GetFileName(FileUrl);
            if (FileName == "")
            {
                Console.WriteLine("获取文件名失败");
                return "";
            }
        
            string FilePath = FloderPath + FileName;
            using (WebClient DownloadWebClient = new WebClient())
            {
                DownloadWebClient.Headers = headers;
                try
                {
                    DownloadWebClient.DownloadFile(new Uri(FileUrl), FilePath);
                }
                catch (Exception ex)
                {
                    PrintLog.Log(ex);

                }
            }

            return FilePath;
        }

        /// <summary>
        ///  文件下载  返回文件的byte流
        /// </summary>
        /// <param name="FileUrl"></param>
        /// <returns></returns>
        public byte[] ByteDownload(string FileUrl)
        {
            return ByteDownload(FileUrl, new WebHelper().PcWebHeader());
        }

        /// <summary>
        /// 文件下载  返回文件的byte流
        /// </summary>
        /// <param name="FileUrl"></param>
        /// <param name="headers"></param>
        /// <returns></returns>
        public byte[] ByteDownload(String FileUrl, WebHeaderCollection headers)
        {
            byte[] ImgData = null;
            using (WebClient DownloadWebClient = new WebClient())
            {
                DownloadWebClient.Headers = headers;
                try
                {
                    ImgData = DownloadWebClient.DownloadData(new Uri(FileUrl));
                }
                catch (Exception ex)
                {
                    PrintLog.Log(ex);
                }
            }
            return ImgData;
        }

        /// <summary>
        /// 初始化文件名
        /// </summary>
        /// <param name="FileUrl"></param>
        /// <param name="DefaultFileName"></param>
        /// <returns></returns>
        private static string InitFileName(string FileUrl, string DefaultFileName)
        {
            Console.WriteLine(FileUrl);
            String Filename = "";
            if (DefaultFileName != "")
                Filename = DefaultFileName;
            else
            {
                Filename = new WebHelper().CreateFilePath(FileUrl, StaticValue.ImgTemp1);
            }

            return Filename;
        }

        /// <summary>
        /// 获取http响应状态码的类，需要连接
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static bool GetStatusCode(String url)
        {
            HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(url);
            //     httpReq.Referer = "https://www.pixiv.net/member_illust.php?mode=medium&illust_id=" + Path.GetFileNameWithoutExtension(url);
            httpReq.Host = new Uri(url).Host;
            httpReq.AllowAutoRedirect = true;//这里很重要，如果你跟随和不跟随重定向得到的结果不同，由于我项目需要跟随重定向，故已经跟随。如果不需要请改为false
            httpReq.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36";

            try
            {
                using (HttpWebResponse httpRes = (HttpWebResponse)httpReq.GetResponse())
                {
                    Console.WriteLine("响应码为：" + httpRes.StatusCode);
                    if (httpRes.StatusCode == HttpStatusCode.OK)
                    {
                        Console.WriteLine(httpRes.StatusCode);

                        return true;
                    }

                    Console.WriteLine("StatusCode" + httpRes.StatusCode);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                ///404 403之类的错误会在这里出现
            }
            return false;
        }

        /// <summary>
        ///电脑请求头
        /// </summary>
        /// <param name="FileUrl"></param>
        /// <returns></returns>
        public WebHeaderCollection PcWebHeader()
        {
            WebHeaderCollection webHeaderCollection = new WebHeaderCollection();
            webHeaderCollection.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36");

            webHeaderCollection.Add("Accept-Language", "zh-TW,zh;q=0.8,en-US;q=0.5,en;q=0.3");
            return webHeaderCollection;
        }
        /// <summary>
        /// 手机请求头，android7.0
        /// </summary>
        /// <returns></returns>
        public WebHeaderCollection MobileWebHeader()
        {
            WebHeaderCollection webHeaderCollection = new WebHeaderCollection();
            webHeaderCollection.Add("User-Agent", "Mozilla/5.0 (Linux; Android 7.0; PLUS Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.98 Mobile Safari/537.36");

            webHeaderCollection.Add("Accept-Language", "zh-TW,zh;q=0.8,en-US;q=0.5,en;q=0.3");
            return webHeaderCollection;
        }

        /// <summary>
        /// 通用获取webheader类
        /// </summary>
        /// <param name="FileUrl"></param>
        /// <returns></returns>
        public WebHeaderCollection PcWebHeader(String FileUrl)
        {
            WebHeaderCollection webHeaderCollection = PcWebHeader();
            String GetHost = "";
            try
            {
                GetHost = new Uri(FileUrl).Host;
                webHeaderCollection.Add("Host", GetHost);
            }
            catch (Exception ex)
            {
                PrintLog.Log(ex);
            }

            return webHeaderCollection;
        }

        /// <summary>
        /// 通用获取webheader类
        /// </summary>
        /// <param name="FileUrl"></param>
        /// <returns></returns>
        public WebHeaderCollection MobileWebHeader(String FileUrl)
        {
            WebHeaderCollection webHeaderCollection = MobileWebHeader();
            String GetHost = "";
            try
            {
                GetHost = new Uri(FileUrl).Host;
                webHeaderCollection.Add("Host", GetHost);
            }
            catch (Exception ex)
            {
                PrintLog.Log(ex);
            }

            return webHeaderCollection;
        }
    }
}